package dubbo.server2.impl.controller;

import dubbo.server2.impl.jibx.Account;
import dubbo.server2.impl.jibx.Birthday;
import org.jibx.runtime.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Jibx 生成bind.xml配置文件 命令参考如下。首先确保已经下载jibx工具包至本地某处，并在target/classes目录下执行命令
 * java -cp D:\java\jibx-1.3.1\lib\jibx-tools.jar org.jibx.binding.generator.BindGen -t D:\java\IdeaProjects\DubboServer\dubbo.server2.impl\src\main\java\dubbo\server2\impl\jibx -v dubbo.server2.impl.jibx.Account dubbo.server2.impl.jibx.Birthday
 * 编译增强类的字节码阶段，请执行maven命令install或jibx的bind命令
 */
@RestController
@RequestMapping("/jibx")
public class JibxController {
    private StringWriter writer = null;
    private StringReader reader = null;
    private final static String CHARSET_NAME = "UTF-8";
    @RequestMapping("/test")
    public String test() {
        Account account=new Account();
        account.setAddress("湖南");
        account.setEmail("dsfwe@sd.com");
        account.setId(11);
        account.setName("刘彻");
        Birthday birthday=new Birthday();
        birthday.setBirthday("19880501");
        account.setBirthday(birthday);
        String xml= null;
        try {
            xml = encode2Xml(account,Account.class);
            decode2Object(xml,Account.class);
        } catch (JiBXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xml;
    }
    private String encode2Xml(Object obj,Class cl) throws JiBXException, IOException {
        IBindingFactory factory = BindingDirectory.getFactory(cl);
        writer = new StringWriter();
        IMarshallingContext mctx = factory.createMarshallingContext();
        mctx.setIndent(2);
        mctx.marshalDocument(obj, CHARSET_NAME, null, writer);
        String xmlStr = writer.toString();
        writer.close();
        System.out.println(xmlStr.toString());
        return xmlStr;
    }

    private <T> T decode2Object(String xmlBody,Class cl) throws JiBXException {
        IBindingFactory factory = BindingDirectory.getFactory(cl);
        reader = new StringReader(xmlBody);
        IUnmarshallingContext uctx = factory.createUnmarshallingContext();
        T obj = (T) uctx.unmarshalDocument(reader);
        return obj;
    }
}
